<?php
/**
 * Created by PhpStorm.
 * User: fengyan
 * Date: 2017/4/8
 * Time: 下午11:43
 */

namespace app\admin\controller;

use app\admin\model;
use think\Db;

class AdminMember extends Admin
{

    /**
     * 自定义模版前缀
     * @var string
     */
    protected $templatePrefix = 'admin/member/';

    /**
     * @var 当前控制器的默认模型
     */
    protected $model;

    /**
     * 初始化操作
     */
    public function _initialize()
    {
        parent::_initialize(); // TODO: Change the autogenerated stub
        $this->model = new model\AdminMember();
    }

    /**
     * 用户列表
     * @return mixed
     */
    public function index()
    {
        $list = model\AdminMember::all(function($query){
            $query->where('status', '>=', 0)->where('id', '<>', 1)->order('id', 'asc');
        });
        cookie('__forward__', $_SERVER['REQUEST_URI']);
        return $this->fetch('index', ['list'=>$list]);
    }

    /**
     * 添加用户页面
     * @return mixed
     */
    public function add()
    {
        $info = $this->model;
        return $this->fetch('edit', ['info'=>$info]);
    }

    /**
     * 修改用户页面
     * @return mixed
     */
    public function edit()
    {
        $id = input('param.id');
        if (empty($id)) {
            $this->error('缺少必要参数', cookie('__forward__'));
        }

        $info = $this->model->get($id);

        return $this->fetch('edit', ['info'=>$info]);
    }

    /**
     * 保存数据
     */
    public function save()
    {
        if (!request()->isPost()) {
            $this->error('错误的请求方式', cookie('__forward__'));
        }

        $id = input('post.id', 0);

        if (empty($id)) {
            if ($_POST['password'] != $_POST['repassword']) {
                $this->error('两次密码输入不同');
            }
            unset($_POST['repassword']);

            $res = $this->model->where('email', '=', input('email'))->find();

            if ($res) {
                $this->error('该帐号已经存在');
                exit;
            }

            $re = $this->model->data($_POST)->allowField(true)->save();
        } else {
            $re = $this->model->allowField(true)->save($_POST, ['id' => $id]);
        }

        if ($re === false) {
            $this->error('操作失败');
        }

        $this->success('操作成功', cookie('__forward__'));
    }
}